//
//  XJRefreshControl.swift
//  下拉刷新
//
//  Created by 452608533 on 16/7/25.
//  Copyright © 2016年 452608533. All rights reserved.
//

import UIKit
enum XJRefreshControlState:Int {
    case Normal = 0
    case Pulling = 1
    case Refreshing = 2
}

private let MyWidth = UIScreen.mainScreen().bounds.width
private let RefreshControlH: CGFloat = 50

class XJRefreshControl: UIControl {
    
    var xjState:XJRefreshControlState = .Normal{
        didSet{
            switch xjState {
            case .Normal:
                messageLabel.text = "正常"
                if oldValue == .Refreshing{
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= RefreshControlH
                        }, completion: { (_) -> Void in
                            self.pullImageView.hidden = false
                            self.indicatorView.stopAnimating()
                    })
                }
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.pullImageView.transform = CGAffineTransformIdentity
                })
            case .Pulling:
                messageLabel.text = "下拉中"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.pullImageView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
            case .Refreshing:
                self.pullImageView.hidden = true
                self.indicatorView.startAnimating()
                messageLabel.text = "刷新中"
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += RefreshControlH
                    }, completion: { (_) -> Void in
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
            }
        }
    }

    var scrollView: UIScrollView?
    
    override init(frame: CGRect) {
        
        super.init(frame: CGRect(x: 0, y: -50, width: UIScreen.mainScreen().bounds.width, height: 50))
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func endRefreshing() {
        xjState = .Normal
    }
    //kvo
    override func willMoveToSuperview(newSuperview: UIView?) {
        guard let scrollView = newSuperview as? UIScrollView else {
            return
        }
        self.scrollView = scrollView
        
        self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        setupRefreshControllState(self.scrollView?.contentOffset.y)
    }
    
    func setupRefreshControllState(contentOffsetY: CGFloat?){
        
        if self.scrollView!.dragging{
            
            let contentInsetTop = self.scrollView?.contentInset.top ?? 0
            
            if contentOffsetY <= -RefreshControlH - contentInsetTop && xjState == .Normal{
                xjState = .Pulling
            }else if contentOffsetY > -RefreshControlH - contentInsetTop && xjState == .Pulling{
                xjState = .Normal
            }
        }else{
            if xjState == .Pulling {
                xjState = .Refreshing
            }
        }
    }
    
    func setupUI() {
        self.backgroundColor = UIColor.brownColor()
        //天剑控件
        addSubview(pullImageView)
        addSubview(indicatorView)
         addSubview(messageLabel)
        //设置约束(系统自带)
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
        
        pullImageView.translatesAutoresizingMaskIntoConstraints = false
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterY, relatedBy: .Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint(item: pullImageView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: -35))
    }

    //懒加载控件
    private lazy var messageLabel:UILabel = {
       let label = UILabel()
        label.text = "正常"
        label.font =  UIFont.systemFontOfSize(15)
        label.textColor = UIColor.whiteColor()
        return label
        
    }()
    //菊花
    private lazy var indicatorView: UIActivityIndicatorView = {
        let indicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
        return indicatorView
    }()
    private lazy var pullImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))

}
